var express = require('express');
var router = express.Router();
var db = require('../../../libs/mysql');
var md5=require("md5");

//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});

router.get('/',function (req,res) {
    res.render('web/user/log');
})

router.post('/',function (req,res) {
    var YD = req.body.YD,
        password = req.body.password;
    password = md5(md5('123456'+'yindume')+'node+mysql'+password+'exit;');
    db.query(`select * from user where YD='${YD}' and password='${password}'`,(err,data) =>{
        if(err){
            res.status(500).send('登录验证').end();
        }else {
            if(data.length == 0){
                res_Data.code = 1;
                res_Data.message = 'YD或密码错误';
                res.json(res_Data);
                return;
            }else {
                res_Data.message = '登录成功';
                res_Data.userInfo = {
                    id: data[0].id,
                    YD : data[0].YD,
                    nickname : escape(data[0].nickname),
                    isAdmin: data[0].isAdmin
                };
                req.cookies.set('userInfo', JSON.stringify(res_Data.userInfo));
                res.json(res_Data);
                return;
            }
        }
    })
})

router.get('/logout',function(req,res){
    req.cookies.set('userInfo', null);
    res.json(res_Data);
})

module.exports = router;